const app = angular.module('app', ['ngSanitize']);
app.controller('ctrl', function ($scope, $http) {
    $scope.content = '';
    $scope.result = {};
    $scope.search = function () {
        $http.get(`/translate/search?content=` + encodeURIComponent($scope.content)).then(function (res) {
            $scope.result = res.data;
        })
    }
    $scope.keyup = function (e) {
        if (e.which === 13) {
            $scope.search();
        } else if (e.which === 27) {
            $scope.content = '';
            $scope.search();
        }
    }
    $scope.newTranslate = function () {
        $scope.param = {
            en: $scope.content,
            cn: '',
        };
        $('#myModal').modal('show')
    }
    $scope.modify = function (idx) {
        $scope.param = {
            id: $scope.result.hits.hits[idx]._id,
            en: $scope.result.hits.hits[idx]._source.en,
            cn: $scope.result.hits.hits[idx]._source.cn,
        };
        $('#myModal').modal('show')
    }
    $scope.submitTranslate = function () {
        if (!$scope.param.cn || !$scope.param.en) {
            alert('请填写英文以及中文');
            return;
        }
        $http.post(`/translate/save`, $scope.param).then(() => {
            $('#myModal').modal('hide');
            $scope.search()
            alert('保存成功');
        })
    }
    $scope.delete = function (idx) {
        const result = confirm('确认么')
        if (true === result) {
            $http.delete(`/translate/delete?id=` + $scope.result.hits.hits[idx]._id).then(() => {
                alert('删除成功');
                $scope.search()
            })
        }
    }
    $scope.init = function () {
        $scope.content = ''
        $scope.search()
    }
    $scope.init();
});